package my.bc.webdav.client;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;

public abstract class AbstractServerInfo implements ServerInfo
{
  public abstract String getInitialPath();
  
//  public URI getUri( String path ) throws URISyntaxException
//  {
//    return new URI( getSchema(), null, getHost(), getPort(), getInitialPath() + path, null, null );
//  }

  public String getUriString( String path ) throws URISyntaxException
  {
    //uri = new URI("http", null, "host", 80, "/help/me/book name+me/", URLEncoder.encode("MY CRZY QUERY! +&+ :)", "UTF-8"), null);
    
    try
    {
      URI uri = new URI( getSchema(), null, getHost(), getPort(), getInitialPath(), null, null );
      //URI uri = new URI( getSchema(), null, getHost(), getPort(), getInitialPath() + URLEncoder.encode( path, "UTF-8" ), null, null );
      String part1 = uri.toASCIIString();
      String part2 = UriUtil.fullEscape( path );
      return appendPath( part1, part2 );
    }
    catch( Exception e )
    {
      e.printStackTrace();
      return null;
    }
  }
  
  public static String appendRawPath( String escapedPath, String rawPath )
  {
    return appendPath( escapedPath, UriUtil.fullEscape( rawPath ) );
  }
  
  public static String appendPath( String part1, String part2 )
  {
    boolean endWithSlash = part1.endsWith( "/" );
    boolean startWithSlash = part2.startsWith( "/" );
    if( endWithSlash != startWithSlash )
      return part1 + part2;
    else if( endWithSlash )
      return part1 + part2.substring( 1 );
    else
      return part1 + "/" + part2;

  }
  
}
